import { createRouter, createWebHashHistory } from 'vue-router'
import store from './dev/store/index'

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes: [
    // { path: '/', component: () => import('./dev/home/index') },
    {
      path: '/',
      component: () => import('./dev/home/index'),
      meta: { requiresAuth: true } // 需要登录
    },
    { path: '/signin', component: () => import('./dev/login/signin') },
    { path: '/signup', component: () => import('./dev/login/signup') },
    { 
      path: '/my', 
      component: () => import('./dev/my/my.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/shop', 
      component: () => import('./dev/my/shop-dynamic.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/pay', 
      component: () => import('./dev/my/pay.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/payment-success', 
      component: () => import('./dev/my/payment-success.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/purchase-history', 
      component: () => import('./dev/my/purchase-history.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/test', 
      component: () => import('./dev/test/test.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/test-result', 
      component: () => import('./dev/test/test-result.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
    { 
      path: '/test-history', 
      component: () => import('./dev/test/test-history.vue'),
      meta: { requiresAuth: true } // 需要登录
    },
  ]
})

// 路由守卫 - 检查用户登录状态
router.beforeEach((to, from, next) => {
  // 检查路由是否需要登录
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (store.state.user.profile.islogin && store.state.user.profile.token) {
      // 已登录，允许访问
      next();
    } else {
      // 未登录，重定向到登录页面
      next('/signin');
    }
  } else {
    // 不需要登录的路由，直接放行
    next();
  }
});

// 让滚动条回到顶部
router.afterEach((to, from, next) => {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
  window.scrollTo(0, 0);
});

export default router;